/**
 * @description:混入对象
 */
export const mymixin = {
  data () {
    return {
      nowpage: 1,
      staffName: '',
      loading: false,
      // 添加删除修改状态---主要通过此状态来判断调用方法
      nowChanceStau: '',
      // 操作按钮的逻辑及展示数据
      addActive: true,
      delActive: false,
      // 表格数据
      tableData: [],
      // 表单数据
      treeData: [],
      // 当前页
      currentPage: 1,
      // 每页的数据条数
      pageSize: 10,
      // 总条数
      totalSize: 0,
      // 总页数
      totalPages: 0,
      rightTableData: [],
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick (picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        },
        {
          text: '最近三个月',
          onClick (picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        },
        {
          text: '最近一年',
          onClick (picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 365);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      // 弹出框添加修改
      titleText: null,
      currentRow: null,
      editObject: {},
      showAddEditDialog: false,
      // 搜索框的显示与隐藏
      activeName: '',
      // 查看视频
      showVideoDialog: false,
      // 查看图片
      showPictureDialog: false,
      // 查看关键字
      showKeyDialog: false,
      // 查看详情原因
      showReasonDialog: false
    }
  },
  created () {
    this.token = sessionStorage.getItem("token");
  },
  watch: {
    nowChanceStau (newval) {
      // 当状态为删除的时候触发删除方法---另外的删除修改添加，通过点击保存，调用方法来实现
      if (newval === 'del') {
        this.delmessage()
      }
    }
  },
  computed: {
    headers () {
      return {
        "loginToken": sessionStorage.getItem("token"),
        "organizationId": sessionStorage.organizationId,
        "sysDataBaseName": "DB_TDW1_OM1"
      }
    }
  },
  methods: {
    exportFile () {
      this.$refs['ExportBtn'].downloadFile()
      console.log(this.$refs['ExportBtn'])
    },
    handleChange (e) {
      console.log(e)
    },
    // table项是否可以被选中
    selectable (row) {
      return !('index' in row)
    },
    // select搜索框
    changeSelect () {
      if (this.activeName === '') {
        this.activeName = '1'
      } else if (this.activeName === '1') {
        this.activeName = ''
      }
    },
    // 填充表格空白行
    addblankmet () {
      let havline = this.tableData.length % this.pageSize
      if (this.tableData.length < this.pageSize) {
        if (havline < this.pageSize) {
          const remain = this.pageSize - havline;
          for (var i = 0; i < remain; i++) {
            this.tableData.push({ 'index': i + this.tableData.length - 1, selectable: true });
          }
        }
      }
    },
    handleCurrentChange (val) {
      this.currentRow = val;
    },
    // 默认全选不选
    toggleNoSelection (rows) {
      if (rows) {
        this.$nextTick(() => {
          rows.forEach(row => {
            this.$refs.tableData.toggleRowSelection(row, false);
          });
        })
      } else {
        this.$refs.tableData.clearSelection();
      }
    },
    // 添加
    add () {
      this.nowChanceStau = 'add'
      this.titleText = "添加"
      this.addActive = false;
      this.delActive = false;
      this.showAddEditDialog = true
    },
    // 删除
    del () {
      this.$confirm("此操作将永久删除该类型, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        
      })
        .then(() => {
          // this.nowChanceStau = 'del'
          this.delmessage()
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
          if (this.tableData.length > 0) {
            if (this.$refs.tableData) {
              this.$refs.tableData.clearSelection();
            } else if (this.$children[0].$children[2].$refs.tableData) {
              this.$children[0].$children[2].$refs.tableData.clearSelection()
            } else {
              this.$children[0].$children[3].$refs.tableData.clearSelection()
            }
          } else if (this.treeData.length > 0) {
            this.$refs.tree.setCheckedKeys([]);
          }
        });
      this.addActive = true;
    },
    // 修改
    edit () {
      this.nowChanceStau = 'edit'
      this.titleText = "修改"
      this.addActive = false;
      this.delActive = false;
      this.showAddEditDialog = true
    },
    // 取消
    cancel () {
      this.nowChanceStau = '';
      this.titleText = ''
      this.rightTableData = [];
      this.editObject = {}
      this.addActive = true;
      this.delActive = false;
      this.showAddEditDialog = false
      this.showPictureDialog = false
      this.showVideoDialog = false
      this.showKeyDialog = false
      this.showReasonDialog = false
      if (this.$refs.tableData) this.$refs.tableData.setCurrentRow()
      if (this.$refs.tableData) this.$refs.tableData.clearSelection()
      if (this.$children[0].$children[2].$refs.tableData) this.$children[0].$children[2].$refs.tableData.clearSelection()
      // if (this.$children[0].$children[3].$refs.tableData) this.$children[0].$children[3].$refs.tableData.clearSelection()
    },
    // 初始化操作栏状态
    resetActionBar () {
      this.nowChanceStau = ''
      this.showAddEditDialog = false;
      this.showPictureDialog = false
      this.showVideoDialog = false
      this.showKeyDialog = false
      this.showReasonDialog = false
      this.addActive = true;
      this.delActive = false;
      if (this.$refs.tableData) this.$refs.tableData.setCurrentRow()
      if (this.$refs.tableData) this.$refs.tableData.clearSelection()
      if (this.$children[0].$children[2].$refs.tableData) this.$children[0].$children[2].$refs.tableData.clearSelection()
      // if (this.$children[0].$children[3].$refs.tableData) this.$children[0].$children[3].$refs.tableData.clearSelection()
    },
    closeDialog () {
      if (this.showAddEditDialog === true || this.showReasonDialog === true) {
        this.queryPageList()
      }
      this.showAddEditDialog = false
      this.showPictureDialog = false
      this.showVideoDialog = false
      this.showKeyDialog = false
      this.showReasonDialog = false
      this.nowChanceStau = '';
      this.titleText = ''
      this.editObject = {}
      this.addActive = true;
      // this.delActive = false;
      if (this.$refs.tableData) this.$refs.tableData.setCurrentRow()
      if (this.$refs.tableData) this.$refs.tableData.clearSelection()
      // if (this.$children[0].$children[3].$refs.tableData) this.$children[0].$children[3].$refs.tableData.clearSelection()
    },
    getFileNameAndDownload (res) {
      let attrs = res.headers['content-disposition'].split(';')
      // 获取文件名
      let fileName = ''
      // 不用管fileName在第几个位置，只要=前面是fileName,就取=后面的值
      for (let i = 0, l = attrs.length; i < l; i++) {
        let temp = attrs[i].split('=')
        if (temp.length > 1 && (temp[0] == 'filename*' || temp[0] == 'filename')) {
          if (temp[0] === 'filename') {
            let n = parseFloat(temp[1]) + ''
            let time = new Date(Number(n))
            fileName = time.toLocaleDateString().replace(/\//g, "-") + " " + time.toTimeString().substr(0, 8) + temp[1].slice(n.length)
          } else {
            fileName = temp[1].split("utf-8''")[1]
          }
          break
        }
      }
      console.log(fileName)
      fileName = decodeURIComponent(fileName)

      // 获取数据类型
      let type = res.headers['content-type'].split(';')[0]
      let blob = new Blob([res.data], { type: type })
      const a = document.createElement('a')

      // 创建URL
      const blobUrl = window.URL.createObjectURL(blob)
      a.download = fileName
      a.href = blobUrl
      document.body.appendChild(a)

      // 下载文件
      a.click()

      // 释放内存
      URL.revokeObjectURL(blobUrl)
      document.body.removeChild(a)
    },
    processName (str) {
      if (null != str && str != undefined) {
        let star = '' //存放名字中间的*
        //名字是两位的就取姓名首位+*
        if (str.length <= 2) {
          return str.substring(0, 1) + "*";
        } else {
          for (var i = 0; i < str.length - 2; i++) {
            star = star + '*'
          }
          return str.substring(0, 1) + star + str.substring(str.length - 1, str.length);
        }
      }
    },
    // 获取当前时间以及日期
    getNowTime () {
      let now = new Date();
      let year = now.getFullYear(); // 获取年
      let month = now.getMonth();// 获取月
      let date = now.getDate();// 获取日
      let hours = now.getHours();// 获取小时
      let minutes = now.getMinutes();// 获取分钟
      let seconds = now.getSeconds();// 获取秒
      month = month + 1;
      month = month.toString().padStart(2, "0");
      date = date.toString().padStart(2, "0");
      return `${year}-${month}-${date} ${hours}:${minutes}:${seconds}`;
    },
    // 时间戳格式化
    formatDateTime (val) {
      var time = new Date(val);
      var year = time.getFullYear(); // 取得4位数的年份
      var month = time.getMonth() + 1; // 取得日期中的月份，其中0表示1月，11表示12月
      var date = time.getDate(); // 返回日期月份中的天数（1到31）
      // var hour = time.getHours(); // 返回日期中的小时数（0到23）
      // var minute = time.getMinutes(); // 返回日期中的分钟数（0到59）
      // var second = time.getSeconds(); // 返回日期中的秒数（0到59）
      return year + "年" + month + "月" + date + "日";
      // return year + "年" + month + "月" + date + " " + hour + ":" + minute + ":" + second;
    },
    // 时间戳格式化
    formatDateTime_ (val) {
      var time = new Date(val);
      var year = time.getFullYear(); // 取得4位数的年份
      var month = time.getMonth() + 1; // 取得日期中的月份，其中0表示1月，11表示12月
      month = month < 10 ? ('0' + month) : month;
      var date = time.getDate(); // 返回日期月份中的天数（1到31）
      date = date < 10 ? ('0' + date) : date;
      // var hour = time.getHours(); // 返回日期中的小时数（0到23）
      // var minute = time.getMinutes(); // 返回日期中的分钟数（0到59）
      // var second = time.getSeconds(); // 返回日期中的秒数（0到59）
      return year + "-" + month + "-" + date;
      // return year + "年" + month + "月" + date + " " + hour + ":" + minute + ":" + second;
    },
    formatDateTimeMHS (val) {
      if (val) {
        var time = new Date(val);
        var year = time.getFullYear(); // 取得4位数的年份
        var month = time.getMonth() + 1; // 取得日期中的月份，其中0表示1月，11表示12月
        month = month < 10 ? ('0' + month) : month;
        var date = time.getDate(); // 返回日期月份中的天数（1到31）
        date = date < 10 ? ('0' + date) : date;
        var hour = time.getHours(); // 返回日期中的小时数（0到23）
        hour = hour < 10 ? ('0' + hour) : hour;
        var minute = time.getMinutes(); // 返回日期中的分钟数（0到59）
        minute = minute < 10 ? ('0' + minute) : minute;
        var second = time.getSeconds(); // 返回日期中的秒数（0到59）
        second = second < 10 ? ('0' + second) : second;
        return year + "-" + month + "-" + date + ' ' + hour + ':' + minute + ':' + second;
        // return year + "年" + month + "月" + date + " " + hour + ":" + minute + ":" + second;}
      }
    },
    dateToFormat (originDate) {
      const dt = new Date(originDate);
      const y = dt.getFullYear();
      const m = (dt.getMonth() + 1 + "").padStart(2, "0");
      const d = (dt.getDate() + "").padStart(2, "0");

      const hh = (dt.getHours() + "").padStart(2, "0");
      const mm = (dt.getMinutes() + "").padStart(2, "0");
      const ss = (dt.getSeconds() + "").padStart(2, "0");

      return `${y}-${m}-${d} ${hh}:${mm}:${ss}`;
    },
    dateToFormattwo (originDate) {
      const dt = new Date(originDate);
      const y = dt.getFullYear();
      const m = (dt.getMonth() + 1 + "").padStart(2, "0");
      const d = (dt.getDate() + "").padStart(2, "0");
      return `${y}-${m}-${d}`;
    },
    deepCopy (obj) {
      const copyObj = {};
      for (let key in obj) {
        if (obj.hasOwnProperty(key) == true) {
          if (obj[key] instanceof Object) {
            copyObj[key] = this.deepCopy(obj[key])
          } else {
            copyObj[key] = obj[key]
          }
        }
      }
      console.log(copyObj);
      return copyObj;
    }
  }
}
